package com.ocom.oauth.auth.app;

import com.alibaba.fastjson.JSON;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.RandomUtil;
import com.ocom.common.vo.app.FindOrRegVo;
import com.ocom.oauth.client.AppClientService;
import com.ocom.security.authentication.YoCiUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 说明：自定义的获取用户信息
 */
@Service
@Slf4j
public class AppCampusUserDetailService {

  @Autowired
  private RedisTemplate redisTemplate;


  @Autowired
  private AppClientService appClientService;

  @Value("${platformSecret}")
  private String platformSecret;


  public UserDetails loadByNameAndCode(String phone, String code) {

    Result result = appClientService.findOrRegByPhoneNum(phone,code);
    if(!result.getCode().equals(200)){
      throw new InvalidGrantException(result.getMsg());
    }
    FindOrRegVo findOrRegVo = JSON.parseObject(JSON.toJSONString(result.getData()), FindOrRegVo.class);

    List<Long> wxAdmin = new ArrayList<>();
    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("ROLE_APP"));
    authorities.add(new SimpleGrantedAuthority("ROLE_WEB"));

    Set<String> permissions = new HashSet<>();
    permissions.add("sys:user:admin");
    String telelePhone = findOrRegVo.getTelelePhone().trim();

    YoCiUser yoCiUser = new YoCiUser(findOrRegVo.getUserId(), Long.valueOf(telelePhone),
        Long.valueOf(telelePhone), telelePhone, permissions, findOrRegVo.getUserName(), "0",
        true, true, true, true, authorities, wxAdmin
        , 0L, 0L, 0l, 0L);
    yoCiUser.setForm(RandomUtil.generateNumber(30));
    return yoCiUser;

  }

}
